-- This file is part of the Fantasy Grounds Open Foundation Ruleset project. 
-- For the latest information, see http://www.fantasygrounds.com/
--
-- Copyright 2008 SmiteWorks Ltd.
--
-- This file is provided under the Open Game License version 1.0a
-- Refer to the license.html file for the full license text
--
-- All producers of work derived from this material are advised to
-- familiarize themselves with the license, and to take special
-- care in providing the definition of Product Identity (as specified
-- by the OGL) in their products.
--
-- All material submitted to the Open Foundation Ruleset project must
-- contain this notice in a manner applicable to the source file type.


function onInit()
	Interface.onHotkeyActivated = onHotkey;
end

function onHotkey(draginfo)
	if draginfo.isType("combattrackernextactor") then
		nextActor();
		return true;
	end
	if draginfo.isType("combattrackernextround") then
		nextRound();
		return true;
	end
end

function createTrackerItem(groupwindow, class, itemdatanode, combatdatanode)
	local trackerclass = CombatManager.getTrackerClass(class);

	if trackerclass then
		window.setDataClassHint(trackerclass);
		local w = groupwindow.list.createNewTrackerWindow(trackerclass);
		
		if w.populate then
			w.populate(itemdatanode, combatdatanode);
		end

		return w;
	end
end

function createGroupFromDrag(draginfo)
	local gw = createWindow();
	
	local class, datanodename = draginfo.getShortcutData();
	local datanode = DB.findNode(datanodename);
	
	if datanode.getChild("name") then
		gw.name.setValue(datanode.getChild("name").getValue());
	end
	
	if datanode.getChild("actors") then
		-- Add actors from the combat
		for n,d in pairs(datanode.getChild("actors").getChildren()) do
			local itemclass, itemdatanodename;
			local itemdatanode;
			
			if d.getChild("link") then
				itemclass, itemdatanodename = d.getChild("link").getValue();
				itemdatanode = DB.findNode(itemdatanodename);
			end
			
			if itemdatanodename and itemdatanodename ~= "" then
				aw = createTrackerItem(gw, itemclass, itemdatanode, d);
			else
				aw = gw.list.createSourcedWindow();
				aw.name.setValue(d.getChild("name").getValue());
			end
		end
	end
end

function onDrop(x, y, draginfo)
	if draginfo.isType("playercharacter") or draginfo.isType("shortcut")  then
		local class, datasource = draginfo.getShortcutData();
		local source = draginfo.getDatabaseNode();

		if source and class == "combat" then
			createGroupFromDrag(draginfo);
		end

		return true;
	end
end

function onSortCompare(w1, w2)
	return string.upper(w1.name.getValue()) > string.upper(w2.name.getValue());
end
